import groovy.json.JsonSlurper


def readHttp(urlConn){
    InputStream inputStream = urlConn.getInputStream();

    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

    BufferedReader reader = new BufferedReader(inputStreamReader);// 读字符串用的。

    String inputLine = null;

    // 使用循环来读取获得的数据，把数据都村到result中了

    String result = ""
    while (((inputLine = reader.readLine()) != null)) {

    // 我们在每一行后面加上一个"\n"来换行

    result += inputLine + "\n";

    }

    reader.close();// 关闭输入流    

    return result
}

def call(total_record, url, bearer_token, scriptId, payload)  {

    Integer tot = total_record as Integer // Convert string to Integer
    HttpURLConnection connection = null;
    if (tot == 1) {
        StringBuilder stringBuilder = new StringBuilder("${url}");
        stringBuilder.append(URLEncoder.encode("${scriptId}", "UTF-8"))
        URL put_url = new URL(stringBuilder.toString());
        connection = (HttpURLConnection) put_url.openConnection()
        connection.setRequestMethod("PUT");
        println("Executing PUT")
    }
    else if (tot == 0) {
        URL post_url = new URL("${url}");
        connection = (HttpURLConnection) post_url.openConnection()
        connection.setRequestMethod("POST");
        println("Executing POST")
    }
    else {
        println("Total records can not be calculated")
    }
    connection.setRequestProperty("Authorization", bearer_token);
    connection.setRequestProperty("Content-Type", "application/json;odata=verbose")
    connection.setRequestProperty("Accept", "application/json")
    connection.setDoOutput(true)
    OutputStream pos = connection.getOutputStream()
    pos.write(payload.getBytes())
    pos.flush();
    pos.close();
    println(connection.responseCode)
    def msg = null
    if(connection.responseCode == 200){
        msg = "Executing Deployment"
        print readHttp(connection)
    }
    else{
        msg = "Error is Connection\n"
        msg += connection.responseCode
    }
    connection.disconnect()
    return msg
}

def callPOST_not_test(url, payload){
    URL post_url = new URL("${url}");
    connection = (HttpURLConnection) post_url.openConnection()
    connection.setRequestMethod("POST");  
    connection.setRequestProperty("Content-Type", "application/json;odata=verbose")
    connection.setRequestProperty("Accept", "application/json")
    connection.setDoOutput(true)
    OutputStream pos = connection.getOutputStream()
    pos.write(payload.getBytes())
    pos.flush();
    pos.close();
    println(connection.responseCode)  
    return readHttp(connection)
}

//println(call(0, "https://www.baidu.com", "", "", ""))

def callZentaoXuanXuan(){

}